package com.jinghua.treatment.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.jinghua.treatment.common.GlobalConstant;
import com.jinghua.treatment.common.controller.BaseController;
import com.jinghua.treatment.common.domain.JSONResult;
import com.jinghua.treatment.entity.SysDoctor;
import com.jinghua.treatment.service.SysDoctorService;
import com.jinghua.treatment.tools.DaYuSMSUtil;
import com.jinghua.treatment.tools.PropertyUtil;
import com.jinghua.treatment.tools.StringUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/doctor")
public class SysDoctorController extends BaseController {


    @ApiOperation(value = "登录页面，医生登录或注册，发送短信")
    @PostMapping(value = "/sengPoneSMS")
    @ResponseBody
    public String sengPoneSMS(String phoneNumber, HttpServletRequest request) {
        Map params = new HashMap();
        params.put("phone", phoneNumber);
        params.put("signName", GlobalConstant.SMS_BANNER);
        params.put("templateCode", PropertyUtil.getConfig("dayu.valicodeTemplateCode"));
        String smsCode = StringUtil.randomStringNumber(6);
        //TODO 目前暂存sesison 中，将来换redis
        session.setAttribute("smsValicode", smsCode);
        params.put("templateParam", "{\"code\":\"" + smsCode + "\"}");
        SendSmsResponse sendSmsResponse  = null;
        try {
            sendSmsResponse = DaYuSMSUtil.sendSms(params);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        System.out.println(sendSmsResponse==null?"":sendSmsResponse.getMessage());
        return "done";
    }

    @ApiOperation(value = "医生登录或注册接口")
    @PostMapping(value = "/regOrLogin")
    @ResponseBody
    public JSONResult regOrLogin(String phoneNumber, String valicode, HttpServletRequest request) {
        String smsValicode = (String) session.getAttribute("smsValicode");
        if (StringUtils.isEmpty(valicode) || !valicode.equals(smsValicode)) {
            return jsonResult(GlobalConstant.FAIL_CODE, "验证码错误！", null);
        }
        SysDoctor sysDoctor = sysDoctorService.regOrLogin(phoneNumber);
        session.setAttribute("currentUser",sysDoctor);
        return jsonResult(GlobalConstant.SUCCESS_CODE, GlobalConstant.SUCCESS_MSG, null);
    }
    @Autowired
    SysDoctorService sysDoctorService;
}
